/**
 * 总控制器
 * 作者（请填写作者并删除此行）
 * 功能:中转操作触发及数据触发
 */
fangimjs.define("controller/totalController", [
    "jquery",
    "event/event",
    "setting/setting",
    "model/modelParse",
    "view/textareaView",
    "view/chatWindowView",
    "view/contactListView",
    "view/totalWindowView",
    "util/util"
], function (require, exports, module) {
    "use strict";
    var $ = require("jquery"),//引用事件
        event = require("event/event"),//引用事件
        util = require("util/util"),//引用事件
        setting = require("setting/setting").getInstance(),//引用配置文件
        modelParse = require("model/modelParse").getInstance(),//引用model层文件
        textareaView = require("view/textareaView"),//引用输入框视图
        chatWindowView = require("view/chatWindowView"),//引入聊天显示窗口视图
        contactListView = require("view/contactListView"),//引入联系人列表视图
        totalWindowView = require("view/totalWindowView");//引入总弹窗操作视图
    var vars = fangimjs.data.vars;
    var config = vars.config;

    var isFlashSocket = true;
    if (config.flash === false) {
        isFlashSocket = false;
    }

    /**
     * 总控制器类
     */
    function totalController() {}
    totalController.prototype = {
        init: function () {
            var that = this;
            that.userState = false;
            that.boxState = false;
            that.readHistory = false;
            //------------------------视图初始化-----------------------------//
            textareaView.init();
            chatWindowView.init();
            contactListView.init();
            totalWindowView.init();
            //------------------------监听视图事件-----------------------------//
            /*添加联系人到最近联系人列表*/
            event.on("view:contacts:add", function (t) {
                // yf: 点击 openChat 会调用
                if (isFlashSocket && !util.getCookie('sfut')) {
                    totalWindowView.showSystemInfo({type: 'sfut_null'});
                    textareaView.lockTextarea();
                } else {
                    that.setContactsState(t, function(data) {
                        modelParse.changeContacts(t, data);
                    });
                }

            });
            /*其他联系人如置业顾问或者经纪人添加到联系人列表*/
            event.on("view:otherContacts:add", function (t) {
                // yf: main.js 调用
                if (isFlashSocket && !util.getCookie('sfut')) {
                    return false;
                }
                that.setContactsState(t.data, function (data) {
                    modelParse.changeOtherContacts(t.data, t.type, data);
                }, t.type);
            });
            /*点击操作窗口状态变化*/
            event.on("view:window:change", function (t) {
                // 修改海外版时，发现没有任何最近联系人，会没有提示
                if (config.type === setting.type.haiwai && isFlashSocket && !util.getCookie('sfut')) {
                    totalWindowView.showSystemInfo({type: 'sfut_null'});
                    textareaView.lockTextarea();
                    return false;
                }
                modelParse.setBoxState(t);
            });
            /*发送消息操作*/
            // yangfan: 提取欢迎语逻辑到modelPase
            event.on("view:msg:send", function(t) {
                modelParse.sendMsg(t);
                modelParse.setNoUserReply('send');
            });
            /*获取历史记录操作*/
            event.on("view:msg:history", function (t) {
                that.readHistory = !that.readHistory;
                var data;
                if (that.readHistory) {
                    data = modelParse.getSelectedContactHistoryMsg();
                } else {
                    data = modelParse.getSelectedContactMsg();
                }
                chatWindowView.updateMsg(data, that.readHistory);
            	// yangfan remove 新样式不需要添加边框
                // textareaView.updateUI(that.readHistory);
            });
            /*联系人列表中选中联系人操作*/
            event.on("view:contact:selected", function (data) {
                if (isFlashSocket && !util.getCookie('sfut')) {
                    totalWindowView.showSystemInfo({type: 'sfut_null'});
                    textareaView.lockTextarea();
                }
                if (modelParse.uiData.selectedContactId != data) {
                    that.setContactsState(data, function (d) {
                        modelParse.setBoxStateAndSelectedContactId(setting.WINDOW_STATUS_MAX, data, d);
                    });
                    // yangfan add 清空已输入文本
                    textareaView.clearTextarea();
                    // yangfan remove 新样式不需要添加边框
                    // that.readHistory = false;
                    // textareaView.updateUI(that.readHistory);
                }
            });
            /*其他联系人列表中选中其他联系人操作*/
            event.on("view:otherContact:selected", function (data) {
                // yf: 防止其他页面退出登录，再点情况
                if (isFlashSocket && !util.getCookie('sfut')) {
                    totalWindowView.showSystemInfo({type: 'sfut_null'});
                    textareaView.lockTextarea();
                }
                that.setContactsState(data.data, function (d) {
                    modelParse.setOtherSelectedContact(data.data, data.type, d);
                }, data.type);
                textareaView.clearTextarea();
            });
            /*点击socket立即重连操作*/
            event.on("view:socket:login", function (data) {
                modelParse.login(data);
            });
            /* yangfan: 添加登出方法，方便切换用户 */
            event.on("socket:userstate:logout", function (data) {
                modelParse.logout();
            });
            //------------------------监听模型事件-----------------------------//
            /*最近联系人列表数据变化*/
            event.on("model:contacts:change", function (t) {
                contactListView.updateContact(t);
            });
            /*其他联系人列表数据变化*/
            event.on("model:otherContacts:change", function (t) {
                contactListView.updateContact(t.data, t.type);
            });
            /*最近联系人在线人数数据变化*/
            event.on('model:contacts:numChange', function (contactData) {
                totalWindowView.changeContactNum(contactData);
                // yangfan add
                contactListView.changeContactNum(contactData);
            });
            /*联系人新消息数据变化*/
            event.on('model:contact:newMsg', function (contactData) {
                contactListView.updateNewMsg(contactData);
                totalWindowView.showNewAlert(contactData);
            });
            /*窗口状态数据变化*/
            event.on("model:window:change", function (t) {
                contactListView.updateWinShow(t);
                totalWindowView.updateWinShow(t);
                that.boxState = totalWindowView.winStatus == setting.WINDOW_STATUS_MAX || totalWindowView.winStatus == setting.WINDOW_STATUS_MAIN;
            });
            /*当前联系人数据变化*/
            event.on("model:singlecontact:change", function (t) {
                chatWindowView.updateInfo(t);
                contactListView.selectContact(t);
            });
            /*消息列表数据发生变化*/
            event.on('model:msg:change', function (data) {
                chatWindowView.updateMsg(data);
            });
            /*发送消息时提示消息*/
            event.on('model:msg:alert', function (t) {
                chatWindowView.showAlert(t);
            });
            /*轮询联系人状态*/
            event.on('model:contacts:pollingState', function () {
                that.pollingContactsState();
            });
            /*查询单个联系人状态*/
            event.on('model:singleContact:state', function (data) {
                that.setContactsState(data, function (d) {
                    modelParse.pollingContactsState(d);
                });
            });
            /*显示系统消息*/
            event.on('socket:systemInfo:show', function (data) {
                totalWindowView.showSystemInfo(data);
                if (data.type === 'verify_failure') {
                    textareaView.lockTextarea();
                }
            });
            /*设置自己的在线状态，data==1在线，其他值为不在线*/
            event.on('socket:state:set', function (data) {
                that.userState = data == 1;
            });

            /**
             * 添加日志信息
             */
            event.on('socket:im:log', function (data) {
                // $.ajax({
                //     url: "http://ditu.test.fang.com/?c=map",
                //     data: {a: 'imlog', data: data[0] + "::" + data[1]},
                //     dataType: 'jsonp',  //类型
                //     jsonp: 'callback', //jsonp回调参数，必需
                //     success: function (data) {
                //         console.log(data);
                //     }
                // });
            });
            //------------------------上传图片相关事件操作-----------------------------//
            //上传成功后，将图片地址写在数据层
            event.on("view:image:upload", function (data) {
                modelParse.setPicData(data);
            });
            //删除图片
            event.on("view:image:del", function (data) {
                modelParse.setPicData('');
                // yf: fix bug 点击删除图片按钮后，再点击发送按钮会发送出图片地址。
                textareaView.showImg('');
            });
            //点击新消息
            event.on("view:newmsg:click", function (data) {
                modelParse.setNewMsgShow();
            });
            //当联系人改变时，图片也改变
            event.on('model:image:change', function (data) {
                textareaView.showImg(data);
            });
            //监听鼠标enter以判断是否为当前窗口
            event.on('view:mouse:enter', function (data) {
                modelParse.setPageActive(data);
            });
            /*发送消息的时候系统提示*/
            event.on('socket:msgstring:show', function (data) {
                chatWindowView.showMsgString(data);
            });

            // yangfan: 用户被禁言
            event.on("view:msg:forbidden", function(t) {
                modelParse.sendMsg(t);
                modelParse.setNoUserReply('send');
            });

            if (vars.config.type === setting.type.xf || vars.config.type === setting.type.esf || vars.config.type === setting.type.haiwai || vars.config.type === setting.type.sfb) {
                modelParse.setBoxState(setting.WINDOW_STATUS_TINY); //初始化uiData数据
            }
        },
        /**
         * 设置使用的socket方式
         * @param socketJsUrl fangimjs的socket模块js路径
         */
        setSocket: function (socketJsUrl) {
            modelParse.setSocket(socketJsUrl);
        },
        /**
         * 轮询最近联系人状态
         */
        pollingContactsState: function () {
            var that = this;
            setInterval(function () {
                if (!that.userState || !that.boxState)return false;
                that.setContactsState(modelParse.contactsDataList, function (data) {
                    modelParse.pollingContactsState(data);
                });
            }, setting.ONLINE_STATE_SEARCH_INTERVAL);
        },
        /**
         * 设置联系人状态
         * @param data
         * @param callback
         * @param type
         */
        setContactsState: function (data, callback, type) {
            if (typeof data === "string") {
                if (type) {
                    data = modelParse.getOtherContactDataById(data, type);
                } else {
                    data = modelParse.getContactDataById(data);
                }
            }
            var obj = {},
                l = 0,
                i = 0;
            var nameArr = [];
            if ($.isArray(data)) {
                if (data.length < 1)return;
                l = data.length;
                for (i = 0; i < l; i++) {
                    nameArr.push(data[i].contactId);
                }
            } else {
                if (!data)return;
                l = 1;
                nameArr.push(data.contactId);
            }
            obj.username = nameArr.join(",");
            $.ajax({
                url: setting.ONLINE_PATH,
                data: obj,
                dataType: 'jsonp',  //类型
                jsonp: 'callback', //jsonp回调参数，必需
                success: function (result) {
                    var stateArr = result.result.split(",");
                    var obj = {};
                    for (i = 0; i < l; i++) {
                        obj[nameArr[i]] = parseInt(stateArr[i]) === 1 ? 1 : 0;
                    }
                    callback(obj);
                },
                error: function () {
                    callback(obj);
                }
            });
        },
        /**
         * 打开对话框
         */
        open: function () {
            totalWindowView.open();
        }
    };
    module.exports = new totalController;
});
